<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/29
 * Time: 18:03
 */

namespace app\mobile\controller;


use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use think\Url;
class Login extends Controller
{
    function __construct()
    {
        if(Request::instance()->action() != 'index'){
            if(empty(session('shop_assignor'))){
                fail('请登录',url('index'));
            }else{
                //$this->redirect(url('percentage'));
            }
        }

    }

    protected $beforeActionList = ['login' => ['except'=>'index']
    ];
    public function index(Request $request)
    {
        $param = Request::instance()->param();
        if($request->isPost()){
            $where['telephone'] = ['eq',$param['telephone']];
            $where['password'] = ['eq',$param['password']];
            $find =  Db::name('shop_assignor')->where($where)->find();
            if($find){
                session('shop_assignor',$find['id']);
                session('name',$find['name']);
                win('登录成功',url('percentage'));
            }else{
                fail('用户名或密码错误');
            }
        }


        return view();
    }

    /**
     * 提成查询
     */
    public function percentage(){
        if(empty(session('shop_assignor'))){
            fail('请登录');
        }
        $param = Request::instance()->param();
        $where = [];
        if(!empty($param['assignor_id'])) $where['sar.assignor_id'] = ['eq',$param['assignor_id']];
        if(!empty($param['title'])) $where['o.order_number'] = ['eq',$param['title']];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['sar.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        $shop_assignor = Db::name('ShopAssignor')->where('shop_id',\session('shop_id'))->select();
        $data = Db::name('shop_assignor_records sar')
            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')
            ->join('order o','sar.order_id = o.id')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id','desc')
            ->where($where)
            ->where('is_agree',2)
            ->where('sar.assignor_id',\session('shop_assignor'))
            ->paginate(10,false,['query' => $param]);
        $shop_assignor = Db::name('ShopAssignor')->where('shop_id',\session('shop_id'))->select();

        $order_count = Db::name('shop_assignor_records sar')
            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')
            ->join('order o','sar.order_id = o.id')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id','desc')
            ->where($where)
            ->where('sar.assignor_id',\session('shop_assignor'))
            ->count();
        $order_sum = Db::name('shop_assignor_records sar')
            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')
            ->join('order o','sar.order_id = o.id')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id','desc')
            ->where($where)
            ->where('sar.assignor_id',\session('shop_assignor'))
            ->order('order_id')
            ->where('is_agree',2)
            ->sum('assignor_price');

        return view('',['shop_assignor' => $shop_assignor,'data' => $data,'order_count' => $order_count,'order_sum' => $order_sum]);
    }


    public function login(){
        halt(1);
    }

    public function out(){
        Session::delete('shop_assignor');

        $this->redirect(Url::build('index'));
    }

    public function daochu(){
        $param = Request::instance()->param();
        $where = [];
        if(!empty($param['assignor_id'])) $where['sar.assignor_id'] = ['eq',$param['assignor_id']];
        if(!empty($param['title'])) $where['o.order_number'] = ['eq',$param['title']];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['sar.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        $shop_assignor = Db::name('ShopAssignor')->where('shop_id',\session('shop_id'))->select();
        $data = Db::name('shop_assignor_records sar')
            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')
            ->join('order o','sar.order_id = o.id')
            ->field('sar.*,sa.name,o.order_number')
            ->order('sar.id','desc')
            ->where($where)
            ->where('sar.assignor_id',\session('shop_assignor'))
            ->select();
        if(!empty($data)){
            foreach ($data as $k => &$v){
                if($v['order_type'] == 1) $v['order_type'] = '商品订单';
                if($v['order_type'] == 2) $v['order_type'] = '服务订单';
                if($v['order_type'] == 3) $v['order_type'] = '礼包订单';
            }
        }
        $name = '个人业绩:'.\session('name');
        $this->push_coupon($data,$name);
        return view('',['shop_assignor' => $shop_assignor,'data' => $data]);
    }

    public function push_coupon($data,$name = 'Excel')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '订单号')
            ->setCellValue('B1', '订单类型')
            ->setCellValue('C1', '服务人员')
            ->setCellValue('D1', '服务金额')
            ->setCellValue('E1', '服务内容')
            ->setCellValue('F1', '服务时间');
        $sheet1 = ['A', 'B', 'C', 'D', 'E','F'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['order_number'])
                ->setCellValue('B' . $num, $v['order_type'])
                ->setCellValue('C' . $num, $v['name'])
                ->setCellValue('D' . $num, $v['assignor_price'])
                ->setCellValue('E' . $num, $v['assignor_content'])
                ->setCellValue('F' . $num, $v['create_time']);
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('个人业绩查询');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

}